﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;
using Sustainalytics.Claims;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.Entities.ConnectionStrings;
using Sustainalytics.Governance.BusinessLogic;
using Sustainalytics.Governance.BusinessLogic.Exceptions;
using Sustainalytics.Utils;
using Sustainalytics.Auth.Claims;
using System.Web.Http.Cors;

namespace Sustainalytics.Governance.Service
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    //[AutoInvalidateCacheOutput]
    //[ClaimsChecker("api/v1/governance")]
    [RoutePrefix("api/v1/governance")]
    [LogControllerFilter(true, true, false)]
    public class GovernanceController : ApiController
    {
        private IGovernanceManager _gManager;
        static IClaimsChecker _claimsChecker;

        public GovernanceController()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(connectionString));
            var clientWarehouseConnectionString = connectionStringsManager.GetConnectionString(ConnectionStringType.ClientDW);
            var governanceWarehouseConnectionString = connectionStringsManager.GetConnectionString(ConnectionStringType.GovernanceDW);
            var connectionStringGovernanceInputFile = ConfigurationManager.ConnectionStrings["GovernanceInputFile"].ConnectionString;

            _gManager = GovernanceManager.CreateGovernanceManager(clientWarehouseConnectionString, governanceWarehouseConnectionString, connectionStringGovernanceInputFile);
            
        }

        static GovernanceController()
        {
            _claimsChecker = new ClaimsChecker();
        }
        public GovernanceController(IGovernanceManager gManager, IClaimsChecker claimsChecker)
        {
            _gManager = gManager;
            _claimsChecker = claimsChecker;
        }

       // [CacheOutput(ServerTimeSpan = 100, ClientTimeSpan = 0, NoCache = true, MustRevalidate = true, Private = true)]
        [Route("{id}")]
        public HttpResponseMessage Get(Guid id)
        {
            HttpResponseMessage response;
            try
            {
                if (!_claimsChecker.ValidateGovernanceClaim(this))
                {
                    return this.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }

                List<int> userUniverseIds = ClaimsPrincipal.Current.Claims.GetUniverseIds(AccountFeature.Governance);

                var result = _gManager.GetProfileByCompany(id, userUniverseIds);

                if (result != null)
                    result.FileName = result.CompanyNameSafeUrl;

                response = Request.CreateResponse(HttpStatusCode.OK, result);
            }
            catch (GovernanceResearchStateFrameworkNotApplicable ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                response = Request.CreateResponse(HttpStatusCode.OK, new { errCode = 7000, message = "Framework not applicable." });
            }
            catch (GovernanceResearchStateInProgressException ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                response = Request.CreateResponse(HttpStatusCode.OK, new { errCode = 7000, message = "Research in progress." });
            }
            catch (CorporateDataGovernanceNotFoundException ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                response = Request.CreateResponse(HttpStatusCode.OK, new { errCode = 7000, message = "Research not available." });
            }
            catch (GovernanceResearchFlagInvalidException ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                response = Request.CreateResponse(HttpStatusCode.OK, new { errCode = 7000, message = "Research not available." });
            }
            catch (GovernanceProfileNotFoundException ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                response = Request.CreateResponse(HttpStatusCode.OK, new { errCode = 7000, message = "Research not available." });
            }
            catch (GovernanceProfileNotInUniversesException ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                response = Request.CreateResponse(HttpStatusCode.OK, new { errCode = 7001, message = "Research available with additional subscription." });
            }
            catch (Exception ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                response = Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
                Console.WriteLine(ex.Message);
            }            
            return response;
        }
    }}